import sys
sys.path.append("../utils")
config_path = "./config.cfg"

import ConfigParser
import time
import re
import datetime as dt
import tables as tb
from collections import Counter

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.dates import date2num
from matplotlib.dates import num2date

def get_h5data(h5file):
    h5file = tb.openFile((h5file), mode='r')
    turbs = h5file.root._v_children
    return turbs

def filter_h5data(turbine_data, filt_strings, startnum=None, steplen=None, stopnum=-1):
    for i, filt in enumerate(filt_strings):
        if i == 0:
            filt_string = filt
        else:
            filt_string += " & " + filt
    filt_data = turbine_data.readWhere(filt_string, start=startnum, stop=stopnum, step=steplen)
    return filt_data

useless_alarms = set(['Bad', 'Pause', 'Comm Fail', 'Emergency', 'I/O Timeout', 'Coercion Failed', 'Stop','Shutdown' 'Pt Created', 'Remote Reboot' , 'Turbine OK', 'Pause over RCS', 'Too many auto-restarts:_____', 'High windspeed: __._ m/s', 'New SERVICE state: _. ____', '[Error 202. ______.______]', 'US error. Turbine stopped'])

def filter_alarm(alarm_string):
    if alarm_string in useless_alarms:
        return False
    else:
        return True
    #match = re.search(r"^(.*thermo.*|.*temp.*|.*termo.*|.*t53.*|.*varm.*|.*cooling.*)*(.*q8.*|.*q7.*|.*breaker.*)*(.*gear.*|.*lubrication.*|.*fine.*)*(.*power.*|.*cur.*|.*volt.*|.*phase.*|.*charge.*)*(.*pitch.*|.*ctrl.*)*(.*yaw.*)*(.*vcms.*|.*vcpm.*|.*vcs.*|.*encoder.*)*(.*rotor.*|.*gen.*|.*rpm.*|.*brake.*)*(.*hydr.*|.*leakage.*|.*pressure.*)*", alarm_string.lower())

def do_hist_of_alarms(table):
    tid_vec1 = [ num2date(x['Time']).year for x in table.where("(AlarmTxt != 'Turbine OK')") if filter_alarm(x['AlarmTxt']) ]
    counts = Counter(tid_vec1)
    total_counts = float(sum(counts.values()))
    ele = []
    count = []
    print counts
    for elem, cnt in counts.items():
        ele.append(elem)
        count.append( cnt / total_counts * 100)

    ax = plt.subplot(111)

    plt.bar(ele, count)

    ind = 2006 + np.arange(6)
    width = 0.4
    plt.xticks(ind + width, ('2006','2007', '2008', '2009', '2010', '2011'))
    plt.ylabel('% of cleaned alarms')
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()
    plt.savefig('alarms.pdf', bbox_inches='tight')

def do_hist_of_all_alarms(table):
    tid_vec1 = [ num2date(x['Time']).year for x in table ]
    counts = Counter(tid_vec1)
    total_counts = float(sum(counts.values()))
    ele = []
    count = []
    print counts
    for elem, cnt in counts.items():
        ele.append(elem)
        count.append( cnt / total_counts * 100)

    plt.figure()
    ax = plt.subplot(111)

    plt.bar(ele, count)

    ind = 2006 + np.arange(6)
    width = 0.4
    plt.xticks(ind + width, ('2006','2007', '2008', '2009', '2010', '2011'))
    plt.ylabel('% of all alarms')
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()
    plt.savefig('all_alarms.pdf', bbox_inches='tight')



def main():
    start_time = time.time()
    config = ConfigParser.ConfigParser()
    config.read(config_path)
    h5file = "alarm-txt-all" + ".h5"
    h5file = "active-alarm-no-all" + ".h5"
    f = tb.openFile((h5file), mode='r')
    table = f.root.data

    do_hist_of_alarms(table)
    do_hist_of_all_alarms(table)
    return



if __name__=='__main__':
    main()
